﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;

namespace server
{
    public partial class Form1 : Form
    {
        int recv = 0;
        int users = 0;
        List<Client> ConnectedUsers = new List<Client>();
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
                    11000);
        Socket newsock = new
          Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
        //
        Thread WaitThread;
        //
        public Form1()
        {
            InitializeComponent();
            WaitThread = new Thread(new ThreadStart(WaitConnection));
            

            newsock.Bind(ipep);
            newsock.Listen(10);
            //Socket client = newsock.Accept();
            //Console.WriteLine("accepting...");

            WaitThread.Start();

            ShowOnlineSrvUsers();
            //Thread MessageThread = new Thread(new ThreadStart(MessageLoop));
            //MessageThread.Start();
        }

        void MessageLoop()
        {
            while (true)
            {
                //ConsoleWrite("Message loop");
            }
        }

        public delegate void ConsoleWriteDelegate(string msg);

        public void ConsoleWrite(string msg)
        {
            if (RichConsole.InvokeRequired == true)
            {
                // this is worker thread
                this.Invoke(new ConsoleWriteDelegate(ConsoleWrite), msg);
            }
            else
            {
                RichConsole.Text += msg;
                //RichConsole.Text += "\n";

                RichConsole.SelectionStart = RichConsole.Text.Length;
                RichConsole.ScrollToCaret();
            }
        }

        void WaitConnection()
        {
            while (true)
            {
                //Thread.Sleep(500);
                
                ConsoleWrite("Waiting for connection...\n");

                ConnectedUsers.Add(new Client(newsock.Accept(),this,"User_" + users.ToString()));
                ConnectedUsers[ConnectedUsers.Count - 1].ID = ConnectedUsers.Count - 1;
                
                ConsoleWrite("Accepting incoming connection...\n");
                users += 1;
                
                ConsoleWrite("Total users:");
                ConsoleWrite(users.ToString());
                ConsoleWrite("\n");
            }
        }

        void ShowOnlineSrvUsers()
        {
            if (ConnectedUsers.Count > 0)
            {
                listBoxUsersOnline.Items.Clear();
                for (int i = 0; i <= ConnectedUsers.Count - 1; i++)
                {
                    listBoxUsersOnline.Items.Add(ConnectedUsers[i].ClientName);
                }
            }
            else
                listBoxUsersOnline.Items.Clear();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= ConnectedUsers.Count - 1; i++)
            {
                ConnectedUsers[i].SendMessage(InputText.Text);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {

            for (int i = 0; i <= ConnectedUsers.Count - 1; i++)
            {
                ConnectedUsers[i].Disconnect();
                ConnectedUsers.Remove(ConnectedUsers[i]);
            }
            System.Environment.Exit(1);
        }

        private void buttonDisconnectUser_Click(object sender, EventArgs e)
        {
            ConnectedUsers[listBoxUsersOnline.SelectedIndex].Disconnect();
            ConnectedUsers.Remove(ConnectedUsers[listBoxUsersOnline.SelectedIndex]);
            ShowOnlineSrvUsers();
        }

        private void buttonReload_Click(object sender, EventArgs e)
        {
            ShowOnlineSrvUsers();
        }

    }
}
